package com.thingcom.delinrobot.main.adddevice;

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizWifiConfigureMode;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.enumration.GizWifiGAgentType;
import com.gizwits.gizwifisdk.listener.GizWifiSDKListener;
import com.thingcom.delinrobot.R;
import com.thingcom.delinrobot.base.BaseBackFragment;
import com.thingcom.delinrobot.utils.CommonDialog;
import com.thingcom.delinrobot.utils.MyLog;
import com.thingcom.delinrobot.utils.PreferencesUtil;
import com.thingcom.delinrobot.utils.ToastUtil;
import com.thingcom.delinrobot.view.BGAProgressBar;
import com.thingcom.delinrobot.view.SimpleToolbar;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.gizwits.gizwifisdk.enumration.GizWifiErrorCode.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING;

import static com.gizwits.gizwifisdk.enumration.GizWifiErrorCode.GIZ_SDK_DEVICE_CONFIG_SEND_FAILED;
import static com.gizwits.gizwifisdk.enumration.GizWifiErrorCode.GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED;
import static com.gizwits.gizwifisdk.enumration.GizWifiErrorCode.GIZ_SDK_DEVICE_CONFIG_TIMEOUT;
import static com.thingcom.delinrobot.Common.Constant.MAC;
import static com.thingcom.delinrobot.main.adddevice.DeviceWifiBackFragment.WIFI_NAME;
import static com.thingcom.delinrobot.main.adddevice.DeviceWifiBackFragment.WIFI_PSW;


/**
 * author : YuFeng
 * e-mail : 923462992@qq.com
 * date   : 2019/11/19
 */
public class DeviceApOpenBackFragment extends BaseBackFragment {
    private static final String TAG = "DeviceApOpenBackFragmen";
    @BindView(R.id.toolbar_ap_open)
    SimpleToolbar toolbarApOpen;
    @BindView(R.id.btn_add_connect)
    Button btnAddConnect;
    @BindView(R.id.cl_ap_open)
    ConstraintLayout clApOpen;
    @BindView(R.id.progressBar)
    BGAProgressBar progressBar;
    @BindView(R.id.cl_ap_connect)
    ConstraintLayout clApConnect;
    private String workSSID;
    private String workSSIDPsw;
    private String ssid;
    private String cutSsid;
    private List<GizWifiGAgentType> types = new ArrayList<>();
    private DeviceListActivity activity;

    public static DeviceApOpenBackFragment newInstance() {
        Bundle bundle = new Bundle();
        DeviceApOpenBackFragment fragment = new DeviceApOpenBackFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        types.add(GizWifiGAgentType.GizGAgentESP);
        //GizWifiSDK.sharedInstance().setListener(mListener);
        workSSID = PreferencesUtil.getInstance(getContext()).getString(WIFI_NAME, null);
        workSSIDPsw = PreferencesUtil.getInstance(getContext()).getString(WIFI_PSW, null);
        MyLog.i("yufeng","onCreate: "+"workSSID: "+workSSID+"workSSIDPsw: "+workSSIDPsw);
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = (DeviceListActivity) context;
    }
    @Override
    public void onResume() {
        super.onResume();

        if (!checkGPSIsOpen()) {
            CommonDialog fragment = CommonDialog.newInstance(getString(R.string.start_tip), getString(R.string.open_position));
            fragment.setCancelable(false);
            if (getFragmentManager() != null) {
                fragment.show(getFragmentManager(), "dialog");
            }
            fragment.setOnOkListener((() -> {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }));
            fragment.setOnCancerListener((this::pop));
        } else {
            ssid = getWIFISSID();
            if(ssid.length()>3){
                cutSsid = ssid.substring(0, 3);
            } else {
                cutSsid = ssid;
            }

            MyLog.i("yufeng","onResume: ");
            MyLog.i(TAG, "onCreate: " + ssid);
            MyLog.i(TAG, "onCreate: " + cutSsid);

            GizWifiSDK.sharedInstance().setListener(new GizWifiSDKListener() {
                @Override
                public void didSetDeviceOnboarding(GizWifiErrorCode result, GizWifiDevice device) {
                    super.didSetDeviceOnboarding(result, device);
                    if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                        // 配置成功

                        ToastUtil.showToast(_mActivity.getApplicationContext(), getString(R.string.success_toast));
                        PreferencesUtil.getInstance(getContext()).putString(MAC,device.getMacAddress());
                        timer.cancel();
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                         // 配置这个之后可以用4G网络
                        //GizWifiSDK.sharedInstance().bindRemoteDevice(uid,token,device.getMacAddress(), DelinApplication.PRODUCT_KEY,DelinApplication.PRODUCT_S,true);
                        //Mode 2 回往回打开fragment
                        start(DeviceApSuccessFragment.newInstance());
                        //      isoncl = true;
                    } else if (result == GIZ_SDK_DEVICE_CONFIG_IS_RUNNING) {
                        MyLog.i("配网","正在配网"+" result:"+result);
                        //  timer.start();
                        // 正在配置
                    } else if (result == GIZ_SDK_DEVICE_CONFIG_SEND_FAILED||result == GIZ_SDK_DEVICE_CONFIG_TIMEOUT||result == GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED){
                        MyLog.i("配网"," result:"+result);
                        // 配置失败
                        ToastUtil.showToast(_mActivity.getApplicationContext(), getString(R.string.fail_toast));
                        timer.cancel();
                        if (clApOpen!=null){
                            activity.runOnUiThread(() -> clApOpen.setVisibility(View.VISIBLE));

                        }
                        if (clApConnect!=null){
                            activity.runOnUiThread(() -> clApConnect.setVisibility(View.GONE));

                        }

                    }
                }
            });
        }
    }

    //有些设备需要gps打开
    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) Objects.requireNonNull(getActivity()).getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_back_ap_open, container, false);
        unbinder = ButterKnife.bind(this, view);
        initToolbar(toolbarApOpen);
        MyLog.i("yufeng","onCreateView: ");
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
        }
    }

    @OnClick(R.id.btn_add_connect)
    public void onViewClicked() {

        if (!cutSsid.equals("Rob")) {
            CommonDialog fragment = CommonDialog.newInstance(getString(R.string.dialog_wifi_tip), getString(R.string.dialog_wifi_suggestion));
            fragment.setCancelable(false);
            if (getFragmentManager() != null) {
                fragment.show(getFragmentManager(), "dialog");

            }
            fragment.setOnOkListener(() -> {
                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                startActivity(intent);
            });
        } else {
           // PreferencesUtil.getInstance(getContext()).putString(AP_NAME, ssid);
            cutSsid = "";
            clApOpen.setVisibility(View.GONE);
            clApConnect.setVisibility(View.VISIBLE);
            //      start(DeviceApConnectBackFragment.newInstance());
            GizWifiSDK.sharedInstance().setDeviceOnboardingDeploy(workSSID, workSSIDPsw, GizWifiConfigureMode.GizWifiSoftAP, ssid, 40, types, true);
            MyLog.i("yufeng"," workSSID:"+workSSID +" workSSIDPsw:"+workSSIDPsw +" ssid:"+ssid  );
            timer.start();
        }
    }

    /**
     * 开始进度
     */

    private CountDownTimer timer = new CountDownTimer(60000, 600) {
        int i = 0;

        @Override
        public void onTick(long millisUntilFinished) {
            i++;
//            String rate = String.format(Locale.getDefault(),"%d%%",i);
//            tvConnectRate.setText(rate);
            progressBar.setProgress(i);
        }

        @Override
        public void onFinish() {
            i = 0;
            progressBar.setProgress(i);
            if (clApConnect!=null){
                clApConnect.setVisibility(View.GONE);
            }
            if (clApOpen!=null){
                clApOpen.setVisibility(View.VISIBLE);
            }
            MyLog.i(TAG, "finish: ");
        }
    };

    /**
     * 获取SSID
     * @return  WIFI 的SSID
     */
//    public String getWIFISSID() {
//        String ssid="<unknown ssid>";
//
//        WifiManager mWifiManager = (WifiManager) _mActivity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        assert mWifiManager != null;
//        WifiInfo info = mWifiManager.getConnectionInfo();
//        ConnectivityManager connManager = (ConnectivityManager) _mActivity.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
//        String name = info.getSSID().replace("\"", "");
//
//        assert connManager != null;
//        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
//        if (networkInfo.isConnected()) {
//            if (networkInfo.getExtraInfo()!=null){
//                ssid = networkInfo.getExtraInfo().replace("\"","");
//            }
//        }
//        if (name. equals("<unknown ssid>")){
//            return ssid;
//        } else {
//            return name;
//        }
//    }
    private String getWIFISSID() {
        String ssid="unknown id";

        if (Build.VERSION.SDK_INT <= 26||Build.VERSION.SDK_INT==28||Build.VERSION.SDK_INT==29) {
            WifiManager mWifiManager = (WifiManager) _mActivity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

            assert mWifiManager != null;
            WifiInfo info = mWifiManager.getConnectionInfo();


            return info.getSSID().replace("\"", "");
        } else if (Build.VERSION.SDK_INT==27){

            ConnectivityManager connManager = (ConnectivityManager) _mActivity.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            assert connManager != null;
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo.isConnected()) {
                if (networkInfo.getExtraInfo()!=null){
                    return networkInfo.getExtraInfo().replace("\"","");
                }
            }
        }
        return ssid;
    }
}
